Generalized Ajax function [migrated]

Posted by TecBrat on Programmers See other posts from Programmers or by TecBrat
Published on 2012-03-29T13:33:43Z Indexed on 2012/03/29 17:41 UTC
Read the original article Hit count: 371

Filed under:
|

Not sure if this question will be considered "off topic". If it is, I'll remove it, but: I hadn't see this yet so I wrote it and would like to know if this is a good approach to it. Would anyone care to offer improvements to it, or point me to an example of where someone else has already written it better?

function clwAjaxCall(path,method,data,asynch)
  {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }    
    if(asynch)
      {
        xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            //alert(xmlhttp.responseText);
            //var newaction=xmlhttp.responseText;
            //alert('Action becomes '+newaction);
            return xmlhttp.responseText;
            }
          }        
      }
    if(method=='GET'){path=path+"/?"+data;}  
    xmlhttp.open(method,path,asynch);
    if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}
    if (!asynch){return xmlhttp.responseText;}

  }

I then called it like

Just Testing
<script type="text/javascript" src="/mypath/js/clwAjaxCall.js"></script>
<script type="text/javascript">
  document.write("<br>More Testing");
  document.write(clwAjaxCall("http://www.mysite.com",'GET',"var=val",false));
</script>

© Programmers or respective owner

Related posts about JavaScript

Related posts about AJAX